"""Helpers operating on datawarehouse.objects."""

import typing


def broken_boot_tests(
    tests: list[typing.Any] | None = None,
    *,
    dw_all: typing.Any = None,
) -> set[typing.Any]:
    """
    Return a set of broken boot tests from builds where _all_ of them failed.

    Arguments:
      tests: list[datawarehouse.objects.KCIDBTest]: tests to evaluate
      dw_all: full checkout data to process known issues attached to tests

    Returns:
      set[datawarehouse.objects.KCIDBTest]: non-FAIL/PASS boot tests of affected builds
    """
    tests = tests if tests is not None else dw_all.tests
    testresults = dw_all.testresults if dw_all else []
    issueoccurrences = dw_all.issueoccurrences if dw_all else []
    build_ids = {t.build_id for t in tests}
    result = set()
    for build_id in build_ids:
        all_tests = {t for t in tests if t.build_id == build_id and not t.waived}
        boot_tests = {t for t in all_tests if t.comment == 'Boot test'}
        # All non-waived tests MISSing is a great indication of a provisioning failure,
        # which must not count as a failed to boot
        if all(t.status == 'MISS' for t in all_tests):
            continue
        # no boot tests at all
        if not boot_tests:
            continue
        for boot_test in boot_tests:
            test_issueoccurrences = [
                i for i in issueoccurrences if boot_test.id == i.test_id or
                any(boot_test.id == tr.test_id and i.testresult_id == tr.id for tr in testresults)
            ]
            # some kernel booted
            if boot_test.status in {'FAIL', 'PASS'}:
                break
            # the boot test was triaged
            if test_issueoccurrences and all(not o.is_regression for o in test_issueoccurrences):
                break
        else:
            result |= boot_tests
    return result
